import os

from sc_engine.apps import messages as msgs
from sc_engine.repositories import Repository, use
from sc_engine.repositories.waiting import WaitingDataRepository
from sc_engine.repositories.stores import PickleFileStore

def make_app(app_name, root_config, config):
    data_directory = root_config['data_directory']

    store_filename = os.path.join(data_directory, app_name)
    store = PickleFileStore(store_filename)
    repo = Repository(store)

    app = ManualYouTubeLinkConverterApp(repo)

    return {
        msgs.ProleagueMatchIdAnnouncement : app.proleague_id,
        msgs.ManualProleagueYouTubeLinkAnnouncement : app.proleague,
    }

class ManualYouTubeLinkConverterApp(object):
    """Convert a verbose ManualYouTubeLink message into a sparse one.

    Typically, a manual youtube link is made using the league name, stage path,
    and other information on the match and game being commented on. However,
    link messages use the match_id, which is generated at run time and may be
    different if the entire engine is run from scratch. This app simply converts
    one type of message into the other when the match id is generated.
    """
    def __init__(self, repo):
        self.repo = repo

    @use('repo', 'matches', 'waiting')
    def proleague_id(self, msg, matches, waiting):
        key = (msg.league, tuple(msg.stage_path), msg.team_one, msg.team_two)

        matches[key] = msg.match_id
        
        if not key in waiting:
            return

        output = []

        for data in waiting[key]:
            msg = msgs.ManualYouTubeLinkAnnouncement(data['video_id'],
                data['part_number'], msg.match_id, data['game_number'])
            output.append(msg)

        del waiting[key]

        return output

    @use('repo', 'matches', 'waiting')
    def proleague(self, msg, matches, waiting):
        key = (msg.league, tuple(msg.stage_path), msg.team_one, msg.team_two)

        if key in matches:
            match_id = matches[key]

            return msgs.ManualYouTubeLinkAnnouncement(msg.video_id,
                    match_id, msg.game_number)
        else:
            data = {
                'video_id': msg.video_id,
                'part_number': msg.part_number,
                'game_number': msg.game_number,
            }

            waiting_data = waiting.setdefault(key, [])
            waiting_data.append(data)


